<?php
namespace Modules\Admin\Services;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use EasyWeChat\Factory;
class UserService  
{
	
	/**
     * @name  获取用户所有信息
     */
    public function get_user_info($data)
    { 
		//微信登录
		if($data['type'] == 2){
			if($data['provider'] == 1){
				$res = $this->mimi_user_info($data);
			}else if($data['provider']==4){
				$res = $data;
			}else if($data['provider']==3){
				$res = $data;
			}
		}
		return $res;
    }
	/**
     * @name  小程序获取登录信息
	 * @data  参数内容包含  code iv encryptData
	 * @return 返回详细用户信息
     */
    public function mimi_user_info($data)
    {
		$new_mini = $this->mimi_code($data['code']);
		if(isset($new_mini['errcode'])){
			return ['code'=>$new_mini['errcode'],'msg'=>$new_mini['errmsg']];
		}
		$config = config('wechat.mini_program.default');
		$mini = Factory::miniProgram($config);
		$decrypted_data = $mini->encryptor->decryptData($new_mini['session_key'], $data['iv'],$data['encryptData']);
        return $decrypted_data;
    }
	/**
     * @name  小程序获取open_id和session_key
	 * @code  小程序code码
	 * @return 返回 session_key open_id 
     */
    public function mimi_code($code)
    {
		$config = config('wechat.mini_program.default');
		$mini = Factory::miniProgram($config);
		$new_mini = $mini->auth->session($code);
        return $new_mini;
    } 
	/**
     * @name 设置token
     */
	public function set_token($data){ 
		if (! $token = JWTAuth::attempt($data)){  
            return [];
        }
		return $this->respond_with_token($token);
	}
	/**	 
	 * @name  我的信息	 
	 */
	public function my(){
		try {
            JWTAuth::parseToken()->authenticate();
		} catch (TokenExpiredException $e) {
            return [
                'code' => 1003,
                'msg' => 'token 过期' , //token已过期
            ];
 
        }catch (TokenInvalidException $e) {
			return false;
        } catch (JWTException $e) {
            return false;
        }
		return JWTAuth::parseToken()->touser();
	}
	/**	 
	 * @name  退出登录
	 */
    public function logout()
    {
        JWTAuth::parseToken()->invalidate();
    }
	/**	 
	 * @name  刷新	 
	 */
    public function refresh()
    {
        return $this->respond_with_token(JWTAuth::parseToken()->refresh());
    }	
	/**
     * @name 组合token数据
     */
	protected function respond_with_token($token)
    {
        return [
				'token' => $token,
				'token_type' => 'bearer',
				'expires_in' => JWTAuth::factory()->getTTL() * 60
			];
    }
}
